package com.fg.pro.sys.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fg.pro.model.sys.entity.SysMenu;
import com.fg.pro.model.sys.entity.SysRoleMenu;
import com.fg.pro.sys.dao.SysRoleDao;
import com.fg.pro.model.sys.entity.SysRole;
import com.fg.pro.sys.service.SysMenuService;
import com.fg.pro.sys.service.SysRoleMenuService;
import com.fg.pro.sys.service.SysRoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色(SysRole)表服务实现类
 *
 * @author makejava
 * @since 2025-07-17 10:10:47
 */
@Service("sysRoleService")
public class SysRoleServiceImpl extends ServiceImpl<SysRoleDao, SysRole> implements SysRoleService {

    @Autowired
    SysMenuService sysMenuService;

    @Autowired
    SysRoleMenuService sysRoleMenuService;



    @Override
    public PageInfo getPage(Integer pageNum, Integer pageSize, String roleName) {
        PageHelper.startPage(pageNum, pageSize);
        List<SysRole> list = query().eq(StrUtil.isNotBlank(roleName),"role_name", roleName).orderByDesc("create_time").list();
        PageInfo<SysRole> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public List<SysMenu> getAllMenuTree() {
        List<SysMenu> tree = sysMenuService.getTree();
        return tree;
    }

    @Override
    public List<Long> getMenuIdById(Long roleId) {
        return sysMenuService.getMenuIdById(roleId);
    }


    @Override
    public Boolean updateMenu(Long roleId, List<Long> menuIdList) {
        QueryWrapper<SysRoleMenu> sysRoleMenuQueryWrapper = new QueryWrapper<>();
        sysRoleMenuQueryWrapper.eq("role_id",roleId);
        sysRoleMenuService.remove(sysRoleMenuQueryWrapper);
        List<SysRoleMenu> list = menuIdList.stream().map(menuId -> {
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setRoleId(roleId);
            sysRoleMenu.setMenuId(menuId);
            return sysRoleMenu;
        }).collect(Collectors.toList());
        boolean save = sysRoleMenuService.saveBatch(list);
        return save;
    }
}

